package com.keyleaf.up.document;


import com.keyleaf.up.document.model.OfficeConfig;
import lombok.extern.slf4j.Slf4j;
import org.jodconverter.core.office.InstalledOfficeManagerHolder;
import org.jodconverter.core.office.OfficeUtils;
import org.jodconverter.local.office.LocalOfficeManager;
import org.jodconverter.local.office.LocalOfficeUtils;

import java.io.File;
import java.util.Arrays;

/**
 * @author keyleaf
 * @since 2025/6/5
 **/
@Slf4j
public class OfficeManager {

    private LocalOfficeManager localOfficeManager;

    public void start(OfficeConfig officeConfig) {
        File officeHome = LocalOfficeUtils.getDefaultOfficeHome();
        try {
            String[] portsString = officeConfig.getServerPorts().split(",");
            int[] ports = Arrays.stream(portsString).mapToInt(Integer::parseInt).toArray();
            long timeout = officeConfig.getTaskTimeout() * 60 * 1000;
            long taskExecutionTimeout = officeConfig.getTaskExecutionTimeout() * 60 * 1000;
            localOfficeManager = LocalOfficeManager.builder()
                    .processRetryInterval(3000L)
                    .officeHome(officeHome)
                    .portNumbers(ports)
                    .processTimeout(timeout)
                    .maxTasksPerProcess(officeConfig.getMaxTasksPerProcess())
                    .taskExecutionTimeout(taskExecutionTimeout)
                    .build();
            localOfficeManager.start();
            InstalledOfficeManagerHolder.setInstance(localOfficeManager);
            log.info("OfficeManager 启动成功");
        } catch (Exception e) {
            log.error("启动office组件失败，请检查office组件是否可用", e);
            throw new RuntimeException("启动office组件失败，请检查office组件是否可用", e);
        }
    }

    public void stop() {
        if (null != localOfficeManager && localOfficeManager.isRunning()) {
            log.info("Shutting down office process");
            OfficeUtils.stopQuietly(localOfficeManager);
        }
    }
}
